import httplib, urllib, re, socket, time

def getResponse(connection, parameters, headers):
	return tryResponse(connection, parameters, headers, 3)

def tryResponse(connection, parameters, headers, tries):
	try:
		connection.request("POST", "/servlet/schoolsource.command.StudentParentAccessCMD", parameters, headers)
		response = connection.getresponse().read()
		connection.close()
		return response
	except httplib.HTTPException, inst:
		print "An HTTPException occurred while trying to communicate with the host"
		print "connection: " + str(connection)
		print "parameters: " + str(parameters)
		print "headers: " + str(headers)
		print inst
		return None
	except socket.error, inst:
		print "Socket error"
		print "connection: " + str(connection)
		print "parameters: " + str(parameters)
		print "headers: " + str(headers)
		print inst
		try:
			connection.close()
		except:
			print "Could not close the connection"
		if tries == 0:
			return None
		else:
			time.sleep(4)
			return tryResponse(connection, parameters, headers, tries - 1)


def testStudent(conn, headers):
	iter = 0
	for i in range(0, 41, 2):
		#print "Student ID: " + str(i + 1000)
		#Student logs in
		#//////////////////////////////////////////////////////////////
		params = urllib.urlencode({'STUDENTID': str(i + 1000), 'SCHOOLNAME': 'demo', 'submitlogin': 'Login', 'USR_PASSWORD': 'student', 'USRTYPE': 'STUDENT', 'PARENTID': ''})
		response = getResponse(conn, params, headers)
		iter = iter + 1
		tokenPattern = re.compile("<INPUT TYPE=\"HIDDEN\" NAME=\"TOKEN\" VALUE=\"(\d*)\">")
		match = tokenPattern.search(response)
		if None == match or None == match.group(1):
			print "Could not find token. Aborting..."
			return iter
		token = match.group(1)
		#print token
		for j in range(0, 5):
			#View classes
			#//////////////////////////////////////////////////////////////
			params = urllib.urlencode({'CURRENT': 'CLASSINFO', 'PARAM': j, 'LINKCLICKED': 'CLASSINFO', 'TOKEN': token, 'SCHOOLNAME': 'demo', 'CLASSNUM': j, 'USRTYPE': 'STUDENT'})
			response = getResponse(conn, params, headers)
			iter = iter + 1
			#print response
			mailPattern = re.compile('setSelected\(0\)\;goToNextPage\(\'MAILLINK\'')
			mailmatch = mailPattern.search(response)

			while mailmatch:
				#Read first email
				params = urllib.urlencode({'TOKEN':  token, 'SCHOOLNAME':  'demo', 'USRTYPE': 'STUDENT', 'CURRENT':  'SUBFRAME', 'PARAM':  '0', 'LINKCLICKED':  'MAILLINK', 'CLASSNUM':  j})
				response = getResponse(conn, params, headers)
				iter = iter + 1

				classPattern = re.compile("<INPUT TYPE=\"HIDDEN\" NAME=\"CLASSID\" VALUE=\"(\d*)\">")
				classMatch = classPattern.search(response)
				if None == classMatch or None == classMatch.group(1):
					print "Could not find class id. Aborting"
					print str(params)
					return iter
				class_id = classMatch.group(1)

				studentPattern = re.compile("<INPUT TYPE=\"HIDDEN\" NAME=\"CT_TO_ID\" VALUE=\"(\d*)\">")
				studentMatch = studentPattern.search(response)
				student_id = studentMatch.group(1)
				if None == studentMatch or None == studentMatch.group(1):
					print "Could not find student id. Aborting"
					print str(params)
					return iter

				# Reply to mail
				#//////////////////////////////////////////////////////////////
				params = urllib.urlencode({'CURRENT':  'SUBFRAME', 'MAILNUM':  '0', 'PARAM':  '0', 'ASSIGNEDRECIPIENTS': '', 'LINKCLICKED':  'Reply', 'FORMFROMSTUDENT':  'TRUE', 'TOKEN':  token, 'SCHOOLNAME':  'demo', 'CT_FROM_ID':  '84', 'CLASSNUM':  j, 'FORMFROMPARENT':  'FALSE', 'CT_TO_ID':  student_id, 'CLASSID':  class_id, 'USRTYPE':  'STUDENT'})
				response = getResponse(conn, params, headers)
				iter = iter + 1
				#print response

				#Send email
				#//////////////////////////////////////////////////////////////
				params = urllib.urlencode({'CURRENT':  'SUBFRAME', 'CLASS_ASSIGNED_ID': class_id, 'PARAM': '', 'ASSIGNEDRECIPIENTS': '84', 'MSG_SUBJECT': 'RE: Test 2', 'LINKCLICKED': '', 'FORMFROMSTUDENT': 'TRUE', 'TOKEN':  token, 'SCHOOLNAME': 'demo', 'CT_FROM_ID': student_id, 'CLASSNUM': j, 'FORMFROMPARENT': 'FALSE', 'BUTTONCLICKED': 'Send', 'CT_TO_ID': '84', 'MSG_BODY': 'This is a reply\r\n\r\n<---- original message ---->\r\nThis is a test email to all students in the class.\r\n123456789012345678901234567890123456789012345678901234567890\r\n123456789012345678901234567890123456789012345678901234567890\r\n123456789012345678901234567890123456789012345678901234567890\r\n123456789012345678901234567890123456789012345678901234567890\r\n123456789012345678901234567890123456789012345678901234567890\r\n123456789012345678901234567890123456789012345678901234567890\r\n\r\n\r\n', 'USRTYPE': 'STUDENT'})
				response = getResponse(conn, params, headers)
				iter = iter + 1
				#print response

				#Refresh
				#//////////////////////////////////////////////////////////////
				params = urllib.urlencode({'TOKEN': token, 'SCHOOLNAME': 'demo', 'USRTYPE': 'STUDENT', 'CURRENT': 'CLASSINFO', 'PARAM': '-1', 'LINKCLICKED': 'Refresh', 'CLASSNUM': j})
				response = getResponse(conn, params, headers)
				iter = iter + 1
				#print response

				#Delete first email
				params = urllib.urlencode({
				'MAILNUM': '0', 'TOKEN': token, 'SCHOOLNAME': 'demo', 'FORMFROMPARENT': 'FALSE', 'USRTYPE': 'STUDENT', 'CURRENT': 'SUBFRAME', 'PARAM': '0', 'ASSIGNEDRECIPIENTS': '', 'LINKCLICKED': 'DELMAIL', 'FORMFROMSTUDENT': 'TRUE', 'CT_FROM_ID': student_id, 'CLASSNUM': j, 'CT_TO_ID': '84'})
				response = getResponse(conn, params, headers)
				iter = iter + 1
				#print response

				params = urllib.urlencode({'CURRENT': 'CLASSINFO', 'PARAM': j, 'LINKCLICKED': 'CLASSINFO', 'TOKEN': token, 'SCHOOLNAME': 'demo', 'CLASSNUM': j, 'USRTYPE': 'STUDENT'})
				response = getResponse(conn, params, headers)
				iter = iter + 1
				#print response
				mailPattern = re.compile('setSelected\(0\)\;goToNextPage\(\'MAILLINK\'')
				mailmatch = mailPattern.search(response)

			#Refresh
			#//////////////////////////////////////////////////////////////
			params = urllib.urlencode({'TOKEN': token, 'SCHOOLNAME': 'demo', 'USRTYPE': 'STUDENT', 'CURRENT': 'CLASSINFO', 'PARAM': '-1', 'LINKCLICKED': 'Refresh', 'CLASSNUM': j})
			response = getResponse(conn, params, headers)
			iter = iter + 1
			#print response

			#View homework
			#//////////////////////////////////////////////////////////////
			params = urllib.urlencode({'TOKEN': token, 'SCHOOLNAME': 'demo', 'USRTYPE': 'STUDENT', 'CURRENT': 'SUBFRAME', 'PARAM': '0', 'LINKCLICKED': 'HWLINK', 'CLASSNUM': j})
			response = getResponse(conn, params, headers)
			iter = iter + 1
			#print response

			#Student progress report
			#//////////////////////////////////////////////////////////////
			params = urllib.urlencode({'CURRENT': 'SUBFRAME', 'PARAM': '', 'LINKCLICKED': 'PROGRESSLINK', 'TOKEN':  token, 'SCHOOLNAME': 'demo', 'CLASSNUM': j, 'USRTYPE': 'STUDENT'})
			response = getResponse(conn, params, headers)
			iter = iter + 1
			#print response

		#Logout
		#//////////////////////////////////////////////////////////////
		params = urllib.urlencode({'USRTYPE': 'STUDENT', 'CURRENT': 'CLASSINFO', 'LINKCLICKED': 'LOGOUT', 'TOKEN': token, 'SCHOOLNAME': 'demo', 'PARAM': '-1', 'CLASSNUM': '0'})
		response = getResponse(conn, params, headers)
		iter = iter + 1
		#print response
	return iter
